package cn.stylefeng.roses.seata.demo.order.modular.controller;

import cn.hutool.core.util.RandomUtil;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.seata.demo.order.modular.service.OrderTblService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * 订单控制器
 *
 * @author fengshuonan
 * @date 2021/8/29 10:49
 */
@RestController
@Slf4j
public class OrderController {

    /**
     * 用户的账户id，用来扣减用户的余额
     */
    private static final String USER_ID = "U100001";

    @Resource
    private OrderTblService orderTblService;

    /**
     * 创建用户订单
     *
     * @param userId        用户id
     * @param commodityCode 商品编码
     * @param orderCount    订单数量
     * @author fengshuonan
     * @date 2021/8/29 10:51
     */
    @PostMapping(value = "/order")
    public ResponseData<?> order(@RequestParam("userId") String userId,
                              @RequestParam("commodityCode") String commodityCode,
                              @RequestParam("orderCount") int orderCount) {

        // 打印分布式事务id
        log.info("Order Service Begin ... xid: " + RootContext.getXID());

        // 插入实体
        orderTblService.placeOrder(userId, commodityCode, orderCount);

        // 模拟随机错误
        if (RandomUtil.randomBoolean()) {
            throw new RuntimeException("this is a mock order Exception");
        }

        return new SuccessResponseData<>();
    }

}
